<template>
  <div>
    <NavigationBar />
    <div class="page-container">
      <div class="adoption-container">
        <div class="adoption-progress">
          <h2>领养进度</h2>
          <p class="subtitle">您正在领养: <strong>{{ selectedPet.name }}</strong></p>
          <div class="progress-container">
            <div class="requirements-notice">
              <h4>领养基本条件：</h4>
              <ul>
                <li>月收入≥3000元</li>
                <li>负债情况下需拥有自有房产</li>
                <li>稳定的就业状态（在职或退休）</li>
                <li>同住家庭成员需同意领养</li>
              </ul>
              <p class="warning">不符合条件的申请将被自动拒绝</p>
            </div>
            <div class="progress-steps">
              <div v-for="(step, index) in steps" :key="index"
                :class="['step', { 'active': currentStep >= index + 1, 'completed': currentStep > index + 1 }]">
                <div class="step-number">{{ index + 1 }}</div>
                <div class="step-title">{{ step.title }}</div>
                <div class="step-description">{{ step.description }}</div>
              </div>
            </div>

            <div class="progress-details">
              <h3>{{ currentStepTitle }}</h3>
              <div class="status-message" :class="statusClass">
                {{ statusMessage }}
              </div>

              <div v-if="currentStep === 1" class="step-content">
                <p>您的申请已提交成功，我们的工作人员将在1-3个工作日内与您联系。</p>
                <p>请保持电话畅通，联系电话: {{ formData.phone }}</p>
              </div>
              <div v-if="currentStep === 2" class="step-content">
                <p>家访安排详情:</p>
                <p v-if="visitScheduled">
                  <strong>时间:</strong> {{ visitDetails.date }} {{ visitDetails.time }}<br>
                  <strong>工作人员:</strong> {{ visitDetails.staff }}<br>
                  <strong>联系电话:</strong> {{ visitDetails.contactPhone }}
                </p>
                <p v-else>家访时间尚未安排，请耐心等待。</p>
              </div>

              <div v-if="currentStep === 3" class="step-content">
                <p>家访结果: {{ homeVisitResult ? '通过' : '未通过' }}</p>
                <p v-if="homeVisitResult">
                  恭喜您通过家访评估！下一步是签署领养协议。
                </p>
                <p v-else>
                  很遗憾，您的居住环境目前不适合领养该宠物。我们的工作人员会与您联系说明具体情况。
                </p>
              </div>

              <div v-if="currentStep === 4" class="step-content">
                <p>请下载并签署领养协议:</p>
                <a href="#" class="download-btn" @click.prevent="downloadAgreement">下载领养协议</a>
                <div class="upload-section" v-if="!agreementSigned">
                  <p>签署完成后请上传:</p>
                  <input type="file" id="agreement-upload" @change="handleAgreementUpload">
                  <label for="agreement-upload" class="upload-btn">选择文件</label>
                  <span v-if="uploadedFileName">{{ uploadedFileName }}</span>
                </div>
                <p v-else class="success-message">协议已成功上传！</p>
              </div>

              <div v-if="currentStep === 5" class="step-content">
                <p>领养费用: ¥{{ adoptionFee }}</p>

                <div class="payment-options">
                  <h4>请选择支付方式:</h4>

                  <div class="payment-method" :class="{ 'selected': paymentMethod === 'online' }"
                    @click="paymentMethod = 'online'">
                    <input type="radio" id="online-payment" v-model="paymentMethod" value="online">
                    <label for="online-payment">线上支付</label>

                    <div v-if="paymentMethod === 'online'" class="payment-details">
                      <div class="qr-code">
                        <img src="@/assets/payment-qr.jpg" alt="支付二维码">
                        <p>请扫描二维码完成支付</p>
                      </div>
                      <div class="payment-platforms">
                        <button class="platform-btn wechat" @click="payWithWeChat">微信支付</button>
                        <button class="platform-btn alipay" @click="payWithAlipay">支付宝支付</button>
                      </div>
                    </div>
                  </div>

                  <div class="payment-method" :class="{ 'selected': paymentMethod === 'offline' }"
                    @click="paymentMethod = 'offline'">
                    <input type="radio" id="offline-payment" v-model="paymentMethod" value="offline">
                    <label for="offline-payment">线下支付(领养时支付)</label>

                    <div v-if="paymentMethod === 'offline'" class="payment-details">
                      <p>请准备好现金或移动支付，在接宠物时完成支付。</p>
                    </div>
                  </div>
                </div>

                <button class="confirm-payment-btn" @click="confirmPayment"
                  :disabled="!paymentConfirmed && paymentMethod === 'online'">
                  {{ paymentMethod === 'online' ? '确认已完成支付' : '继续' }}
                </button>

                <p v-if="paymentMethod === 'online' && paymentConfirmed" class="success-message">
                  支付验证成功！您的领养流程将继续。
                </p>
              </div>

              <div v-if="currentStep === 6" class="step-content final-step">
                <p>恭喜！您的领养申请已完成所有流程。</p>
                <p><strong>接宠时间:</strong> {{ pickupDetails.date }} {{ pickupDetails.time }}</p>
                <p><strong>地点:</strong> {{ pickupDetails.location }}</p>
                <p><strong>联系人:</strong> {{ pickupDetails.contactPerson }} ({{
                  pickupDetails.contactPhone }})</p>
                <p>请携带有效身份证件按时前往。</p>

                <div class="completion-actions">
                  <button class="print-btn" @click="printDetails">打印详情</button>
                  <button class="contact-btn" @click="contactStaff">联系工作人员</button>
                </div>
              </div>
            </div>
          </div>

          <div class="pet-info-card">
            <img :src="getImageUrl(selectedPet.image)" :alt="selectedPet.name" class="pet-image">
            <div class="pet-details">
              <h3>{{ selectedPet.name }}</h3>
              <p><span class="label">类型:</span> {{ selectedPet.type === 'cat' ? '猫' : '狗' }}</p>
              <p><span class="label">性别:</span> {{ selectedPet.gender === '雄' ? '雄性' : '雌性' }}</p>
              <p><span class="label">年龄:</span> {{ selectedPet.age }}岁</p>
            </div>
          </div>
          <!-- 取消领养选项 -->
          <div class="cancel-adoption">
            <p class="warning">
              <strong>警告：</strong>无特殊原因无故取消领养将被拉黑。
            </p>
            <button class="cancel-btn" @click="cancelAdoption">取消领养</button>
          </div>
        </div>
      </div>
    </div>
    <Footer />
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import NavigationBar from '@/components/NavigationBar.vue';
import Footer from '@/components/Footer.vue';

const route = useRoute();
const router = useRouter();

const selectedPet = ref({
  id: null,
  name: '',
  type: '',
  gender: '',
  age: '',
  image: ''
});
const formData = ref({
  name: '',
  phone: '',
  email: '',
  address: '',
  housing: '',
  experience: '',
  reason: ''
});
const steps = ref([
  { title: '申请提交', description: '已收到您的申请' },
  { title: '家访安排', description: '安排工作人员家访' },
  { title: '家访评估', description: '评估居住环境' },
  { title: '签署协议', description: '完成领养协议' },
  { title: '支付费用', description: '完成领养支付' },
  { title: '接宠回家', description: '完成领养流程' }
]);
const currentStep = ref(1);
const statusMessage = ref('您的申请已提交，正在审核中...');
const statusClass = ref('info');
const visitScheduled = ref(false);
const visitDetails = ref({
  date: '',
  time: '',
  staff: '',
  contactPhone: ''
});
const homeVisitResult = ref(null);
const agreementSigned = ref(false);
const uploadedFileName = ref('');
const adoptionFee = ref(300);
const pickupDetails = ref({
  date: '',
  time: '',
  location: '',
  contactPerson: '',
  contactPhone: ''
});
const paymentMethod = ref('online');
const paymentConfirmed = ref(false);
const paymentStatus = ref('');
const paymentQRCode = ref('@/assets/payment-qr.jpg');

const currentStepTitle = computed(() => steps.value[currentStep.value - 1].title);
const paymentDescription = computed(() => paymentMethod.value === 'online' ? '请完成线上支付' : '请在接宠物时完成支付');

const getImageUrl = (imageName) => {
  return new URL(`/src/assets/images/${imageName}`, import.meta.url).href;
};

const simulateProgress = () => {
  setTimeout(() => {
    currentStep.value = 2;
    statusMessage.value = '家访时间安排中...';
    statusClass.value = 'info';

    const visitDate = new Date();
    visitDate.setDate(visitDate.getDate() + 3);
    visitDetails.value.date = visitDate.toISOString().split('T')[0];
    visitDetails.value.time = '14:00-16:00';
    visitDetails.value.staff = '张志愿者';
    visitDetails.value.contactPhone = '13800138000';

    setTimeout(() => {
      visitScheduled.value = true;
      statusMessage.value = '家访已安排: ' + visitDetails.value.date + ' ' + visitDetails.value.time;
      statusClass.value = 'success';

      setTimeout(() => {
        currentStep.value = 3;
        statusMessage.value = '家访评估中...';
        statusClass.value = 'info';

        const isApproved = Math.random() > 0.5; // 50% 的概率通过

        if (isApproved) {
          homeVisitResult.value = true;
          statusMessage.value = '恭喜！家访评估已通过';
          statusClass.value = 'success';

          setTimeout(() => {
            currentStep.value = 4;
            statusMessage.value = '请签署领养协议';
            statusClass.value = 'info';
          }, 2000);
        } else {
          homeVisitResult.value = false;
          statusMessage.value = '很遗憾，您的居住环境目前不适合领养该宠物。我们的工作人员会与您联系说明具体情况。';
          statusClass.value = 'error';
        }
      }, 3000);
    }, 3000);
  }, 2000);
};

const downloadAgreement = () => {
  console.log('下载领养协议');
  const link = document.createElement('a');
  link.href = '/path/to/agreement.pdf';
  link.download = '领养协议.pdf';
  link.click();
};

const handleAgreementUpload = (event) => {
  const file = event.target.files[0];
  if (file) {
    uploadedFileName.value = file.name;
    setTimeout(() => {
      agreementSigned.value = true;
      statusMessage.value = '协议已成功上传！';
      statusClass.value = 'success';

      const pickupDate = new Date();
      pickupDate.setDate(pickupDate.getDate() + 7);
      pickupDetails.value.date = pickupDate.toISOString().split('T')[0];
      pickupDetails.value.time = '10:00-12:00';
      pickupDetails.value.location = 'XX市动物保护中心';
      pickupDetails.value.contactPerson = '李工作人员';
      pickupDetails.value.contactPhone = '13900139000';

      setTimeout(() => {
        currentStep.value = 5;
        statusMessage.value = paymentDescription.value;
        statusClass.value = 'info';
      }, 2000);
    }, 1500);
  }
};

const payWithWeChat = () => {
  paymentStatus.value = 'pending';
  console.log('使用微信支付');
  alert('正在跳转到微信支付...');

  setTimeout(() => {
    paymentStatus.value = 'success';
    paymentConfirmed.value = true;
    statusMessage.value = '微信支付成功！';
    statusClass.value = 'success';
  }, 2000);
};

const payWithAlipay = () => {
  paymentStatus.value = 'pending';
  console.log('使用支付宝支付');
  alert('正在跳转到支付宝支付...');

  setTimeout(() => {
    paymentStatus.value = 'success';
    paymentConfirmed.value = true;
    statusMessage.value = '支付宝支付成功！';
    statusClass.value = 'success';
  }, 2000);
};

const confirmPayment = () => {
  if (paymentMethod.value === 'online' && !paymentConfirmed.value) {
    alert('请先完成支付');
    return;
  }

  if (paymentMethod.value === 'online') {
    statusMessage.value = '支付验证成功！';
    statusClass.value = 'success';
  } else {
    statusMessage.value = '请在接宠物时完成支付';
    statusClass.value = 'info';
  }

  setTimeout(() => {
    currentStep.value = 6;
    statusMessage.value = '领养流程已完成！';
    statusClass.value = 'success';
  }, 1500);
};

const printDetails = () => {
  window.print();
};

const contactStaff = () => {
  alert(`将拨打工作人员电话: ${pickupDetails.value.contactPhone}`);
};

const cancelAdoption = () => {
  const confirmCancel = confirm('您确定要取消领养吗？无特殊原因无故取消领养将被拉黑。');
  if (confirmCancel) {
    localStorage.removeItem('adoptionFormData');
    router.push({ name: 'PetAdoption' });
  }
};

onMounted(() => {
  selectedPet.value.id = route.params.petId;
  selectedPet.value.name = route.query.petName || '未知宠物';
  selectedPet.value.type = route.query.petType || '未知类型';
  selectedPet.value.gender = route.query.petGender || '未知性别';
  selectedPet.value.age = route.query.petAge || '未知年龄';
  selectedPet.value.image = route.query.petImage || 'default-pet.jpg';

  const savedFormData = localStorage.getItem('adoptionFormData');
  if (savedFormData) {
    formData.value = JSON.parse(savedFormData);
  }

  simulateProgress();
});
</script>

<style scoped>
.page-container {
  padding: 20px 0;
  min-height: calc(100vh - 120px);
  display: flex;
  justify-content: center;
  align-items: flex-start;
  background-color: #f5f5f5;
}

.adoption-container {
  width: 90%;
  max-width: 1000px;
  background-color: white;
  border-radius: 15px;
  box-shadow: 0 2px 15px rgba(0, 0, 0, 0.1);
  padding: 30px;
  margin: 20px 0;
}

h2 {
  color: #4a7c59;
  margin-bottom: 20px;
  text-align: center;
  font-size: 1.8rem;
}

.subtitle {
  text-align: center;
  margin-bottom: 30px;
  font-size: 1.1rem;
  color: #666;
}

.pet-info {
  display: flex;
  align-items: center;
  margin-bottom: 30px;
  padding: 15px;
  background-color: #f9f9f9;
  border-radius: 10px;
}

.pet-image {
  width: 120px;
  height: 120px;
  object-fit: cover;
  border-radius: 10px;
  margin-right: 20px;
}

.requirements-notice {
  background-color: #f8f9fa;
  padding: 15px;
  border-radius: 8px;
  margin-bottom: 20px;
  border-left: 4px solid #4a7c59;
}

.requirements-notice h4 {
  color: #4a7c59;
  margin-top: 0;
}

.requirements-notice ul {
  padding-left: 20px;
  margin: 10px 0;
}

.warning {
  color: #ff6b6b;
  font-weight: bold;
}

input:invalid,
select:invalid {
  border-color: #ff6b6b;
}

.pet-details {
  flex: 1;
}

.pet-details p {
  margin: 5px 0;
  color: #555;
}

.label {
  font-weight: bold;
  color: #4a7c59;
  display: inline-block;
  width: 60px;
}

form {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
}

.form-group {
  width: calc(50% - 15px);
  margin-bottom: 20px;
}

.form-group.full-width {
  width: 100%;
}

label {
  display: block;
  margin-bottom: 8px;
  font-weight: bold;
  color: #555;
}

input,
select,
textarea {
  width: 100%;
  padding: 10px 15px;
  border: 1px solid #ddd;
  border-radius: 8px;
  font-size: 0.95rem;
  transition: all 0.3s;
}

input:focus,
select:focus,
textarea:focus {
  outline: none;
  border-color: #4a7c59;
  box-shadow: 0 0 0 2px rgba(74, 124, 89, 0.2);
}

textarea {
  min-height: 100px;
  resize: vertical;
}

.checkbox-label {
  display: flex;
  align-items: center;
  font-weight: normal;
  cursor: pointer;
}

.checkbox-label input {
  width: auto;
  margin-right: 10px;
}

.checkbox-label a {
  color: #4a7c59;
  text-decoration: none;
  margin-left: 5px;
}

.checkbox-label a:hover {
  text-decoration: underline;
}

.form-actions {
  width: 100%;
  display: flex;
  justify-content: center;
  gap: 20px;
  margin-top: 30px;
}

.cancel-btn,
.submit-btn {
  padding: 12px 30px;
  border: none;
  border-radius: 8px;
  font-size: 1rem;
  cursor: pointer;
  transition: all 0.3s;
}

.cancel-btn {
  background-color: #f1f1f1;
  color: #666;
}

.cancel-btn:hover {
  background-color: #e0e0e0;
}

.submit-btn {
  background-color: #4a7c59;
  color: white;
}

.submit-btn:hover {
  background-color: #3a6a49;
}

/* 进度查看样式 */
.adoption-progress {
  width: 100%;
}

.progress-container {
  display: flex;
  margin-top: 30px;
}

.progress-steps {
  width: 250px;
  padding-right: 20px;
  border-right: 1px solid #eee;
}

.step {
  margin-bottom: 25px;
  position: relative;
  padding-left: 40px;
  opacity: 0.6;
}

.step.active {
  opacity: 1;
}

.step.completed {
  opacity: 1;
}

.step-number {
  position: absolute;
  left: 0;
  top: 0;
  width: 30px;
  height: 30px;
  background-color: #ddd;
  color: #666;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: bold;
}

.step.active .step-number {
  background-color: #4a7c59;
  color: white;
}

.step.completed .step-number {
  background-color: #8bc34a;
  color: white;
}

.step-title {
  font-weight: bold;
  margin-bottom: 5px;
  color: #333;
}

.step-description {
  font-size: 0.9rem;
  color: #777;
}

.progress-details {
  flex: 1;
  padding-left: 30px;
}

.payment-options {
  margin: 20px 0;
}

.payment-method {
  padding: 15px;
  margin: 10px 0;
  border: 1px solid #ddd;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s;
}

.payment-method.selected {
  border-color: #4CAF50;
  background-color: #f8f9fa;
}

.payment-method input[type="radio"] {
  margin-right: 10px;
}

.payment-details {
  margin-top: 15px;
  padding: 15px;
  background-color: #f5f5f5;
  border-radius: 5px;
}

.qr-code {
  text-align: center;
  margin: 15px 0;
}

.qr-code img {
  width: 200px;
  height: 200px;
  border: 1px solid #ddd;
}

.payment-platforms {
  display: flex;
  justify-content: center;
  gap: 15px;
  margin-top: 15px;
}

.platform-btn {
  padding: 10px 20px;
  border: none;
  border-radius: 5px;
  color: white;
  cursor: pointer;
  font-weight: bold;
}

.platform-btn.wechat {
  background-color: #09BB07;
}

.platform-btn.alipay {
  background-color: #00AAEE;
}

.confirm-payment-btn {
  margin-top: 20px;
  padding: 12px 25px;
  background-color: #4CAF50;
  color: white;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  font-size: 16px;
}

.confirm-payment-btn:disabled {
  background-color: #cccccc;
  cursor: not-allowed;
}

.status-message {
  padding: 15px;
  border-radius: 8px;
  margin-bottom: 20px;
  font-weight: bold;
}

.status-message.info {
  background-color: #e3f2fd;
  color: #1976d2;
}

.status-message.success {
  background-color: #e8f5e9;
  color: #388e3c;
}

.status-message.warning {
  background-color: #fff8e1;
  color: #ffa000;
}

.status-message.error {
  background-color: #ffebee;
  color: #d32f2f;
}

.step-content {
  background-color: #f9f9f9;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
}

.step-content p {
  margin: 10px 0;
  line-height: 1.6;
}

.download-btn,
.upload-btn,
.print-btn,
.contact-btn {
  display: inline-block;
  padding: 8px 15px;
  background-color: #4a7c59;
  color: white;
  border: none;
  border-radius: 5px;
  margin: 10px 5px 10px 0;
  cursor: pointer;
  text-decoration: none;
  font-size: 0.9rem;
  transition: all 0.3s;
}

.download-btn:hover,
.upload-btn:hover,
.print-btn:hover,
.contact-btn:hover {
  background-color: #3a6a49;
}

input[type="file"] {
  display: none;
}

.upload-btn {
  display: inline-block;
}

.upload-section {
  margin-top: 15px;
}

.success-message {
  color: #388e3c;
  font-weight: bold;
}

.final-step {
  background-color: #e8f5e9;
}

.completion-actions {
  margin-top: 20px;
  display: flex;
  gap: 15px;
}

.pet-info-card {
  display: flex;
  align-items: center;
  margin-top: 40px;
  padding: 15px;
  background-color: #f5f5f5;
  border-radius: 10px;
}

.pet-info-card .pet-image {
  width: 80px;
  height: 80px;
}

.pet-info-card .pet-details h3 {
  margin: 0 0 10px 0;
  color: #4a7c59;
}

/* 领养协议弹窗 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.7);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal-content {
  background-color: white;
  width: 90%;
  max-width: 600px;
  border-radius: 15px;
  padding: 30px;
  position: relative;
  max-height: 80vh;
  overflow-y: auto;
}

.close-btn {
  position: absolute;
  top: 15px;
  right: 15px;
  background: none;
  border: none;
  font-size: 1.8rem;
  cursor: pointer;
  color: #666;
}

.agreement-text {
  margin: 20px 0;
  line-height: 1.8;
}

.agreement-text p {
  margin-bottom: 10px;
}

.agree-btn {
  display: block;
  width: 100%;
  padding: 12px;
  background-color: #4a7c59;
  color: white;
  border: none;
  border-radius: 8px;
  font-size: 1rem;
  cursor: pointer;
  margin-top: 20px;
  transition: all 0.3s;
}

.agree-btn:hover {
  background-color: #3a6a49;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .adoption-container {
    padding: 20px;
  }

  .form-group {
    width: 100%;
  }

  .progress-container {
    flex-direction: column;
  }

  .progress-steps {
    width: 100%;
    padding-right: 0;
    border-right: none;
    border-bottom: 1px solid #eee;
    padding-bottom: 20px;
    margin-bottom: 20px;
    display: flex;
    overflow-x: auto;
  }

  .step {
    min-width: 150px;
    padding-left: 0;
    padding-top: 40px;
    margin-right: 20px;
    margin-bottom: 0;
    text-align: center;
  }

  .step-number {
    left: 50%;
    top: 0;
    transform: translateX(-50%);
  }

  .progress-details {
    padding-left: 0;
  }

  .pet-info,
  .pet-info-card {
    flex-direction: column;
    text-align: center;
  }

  .pet-image {
    margin-right: 0;
    margin-bottom: 15px;
  }
}

@media (max-width: 480px) {
  .form-actions {
    flex-direction: column;
    gap: 10px;
  }

  .cancel-btn,
  .submit-btn {
    width: 100%;
  }

  .completion-actions {
    flex-direction: column;
  }
}
</style>